package com.basker.pisces.redis.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

import com.basker.pisces.spring.SpringApplicationContext;

public class RedisUtils {

    private static final String REDIS_URL_PREFIX = "redis://";

    @SuppressWarnings("unchecked")
    public static byte[] rawKey(RedisTemplate<?, ?> redisTemplate, Object key) {
        Assert.notNull(key, "parameter 'key' is required");
        Assert.notNull(redisTemplate, "parameter 'redisTemplate' is required");

        if (key instanceof byte[]) {
            return (byte[]) key;
        }

        @SuppressWarnings("rawtypes")
        RedisSerializer serializer = redisTemplate.getKeySerializer();
        if (serializer == null) {
            serializer = redisTemplate.getStringSerializer();

        }

        return serializer.serialize(key);
    }

    @SuppressWarnings("unchecked")
    public static byte[] rawValue(RedisTemplate<?, ?> redisTemplate, Object value) {
        Assert.notNull(value, "parameter 'value' is required");
        Assert.notNull(redisTemplate, "parameter 'redisTemplate' is required");

        if (value instanceof byte[]) {
            return (byte[]) value;
        }

        @SuppressWarnings("rawtypes")
        RedisSerializer serializer = redisTemplate.getValueSerializer();
        if (serializer == null) {
            serializer = redisTemplate.getStringSerializer();

        }

        return serializer.serialize(value);
    }

    /**
     * 在key之前加上当前应用的名称
     *
     * @param key
     * @return
     */
    public static String resolveKeyWithApplicationName(String key) {
        String appName = SpringApplicationContext.getInstance().getName();

        if (StringUtils.isEmpty(appName)) {
            return key;
        } else {
            return String.join(":", appName, key);
        }
    }

    public static String resolveUrl(RedisNode node) {
        return REDIS_URL_PREFIX + node.asString();
    }

    public static String resolveUrl(String host, int port) {
        return resolveUrl(new RedisNode(host, port));
    }
}
